package apps.sofftech.twitter;

import com.google.android.gms.internal.mc;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;
import apps.softtech.fastmarket.ActivityRegister;
import apps.softtech.fastmarket.R;
import apps.softtech.fastmarket.model.UserInfo;

public class ActivityLoginTwitter extends Activity {

	public static final String TAG = "ActivityLoginTwitter";

	/**
	 * save nhung cai lien quan toi login twitter
	 */
	SharedPreferences pref;

	private static String CONSUMER_KEY = "S96q8FRvUoz8o7uLVYJiF12jE";
	private static String CONSUMER_SECRET = "bVDTGkK7P9ThKx8X5MpjG7CgsCAtsmWYRFN1iIylvIsYdne1IT";
	private static String PREF_KEY_TWITTER_LOGIN = "isTwitterLoggedIn";

	/*
	 * String to save info of user after login
	 */
	private String userName;
	private String userId;
	private String userDescription;
	private String createAt;
	private String profileUrl;

	Twitter twitter;
	RequestToken requestToken = null;
	AccessToken accessToken;
	private String oauth_url, oauth_verifier;

	WebView web;
	Dialog auth_twitter_dialog;
	ImageView login;

	ProgressDialog progress;

	private Context mContext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_login_twitter);
		mContext = this;

		pref = getPreferences(0);
		SharedPreferences.Editor edit = pref.edit();
		edit.putString("CONSUMER_KEY", CONSUMER_KEY);
		edit.putString("CONSUMER_SECRET", CONSUMER_SECRET);
		edit.putBoolean(PREF_KEY_TWITTER_LOGIN, false);
		edit.commit();
		twitter = new TwitterFactory().getInstance();
		twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);

		init();
		getEvent();

	}

	public void init() {
		login = (ImageView) findViewById(R.id.login);
	}

	/**
	 * get event for button.. in activity
	 */
	public void getEvent() {
		login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				new TokenGet().execute();

				// if (!isTwitterLoggedIn()) {
				// new TokenGet().execute();
				// } else {
				// // user already logged into twitter
				// Toast.makeText(mContext, "Already Logged into twitter",
				// Toast.LENGTH_LONG).show();
				// Intent intent = new Intent(mContext, ActivityRegister.class);
				// SharedPreferences.Editor edit = pref.edit();
				// intent.putExtra(UserInfo.USERNAME, pref.getString("name",
				// ""));
				// intent.putExtra("avatar", pref.getString("avatar", ""));
				// setResult(ActivityRegister.RESULT_TWITTER);
				// ActivityLoginTwitter.this.finish();
				// }

			}
		});
	}

	/**
	 * class prepare to login twitter
	 * 
	 * @author MUI
	 * 
	 */
	private class TokenGet extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			try {
				requestToken = twitter.getOAuthRequestToken();
				oauth_url = requestToken.getAuthorizationURL();
			} catch (TwitterException e) {
				e.printStackTrace();
			}
			return oauth_url;

		}

		@SuppressWarnings("null")
		@Override
		protected void onPostExecute(String oauth_url) {
			super.onPostExecute(oauth_url);
			if (oauth_url != null) {
				Log.e("URL", "oauth _url: " + oauth_url);
				auth_twitter_dialog = new Dialog(mContext);
				auth_twitter_dialog
						.requestWindowFeature(Window.FEATURE_NO_TITLE);

				auth_twitter_dialog
						.setContentView(R.layout.auth_twitter_dialog);
				web = (WebView) auth_twitter_dialog.findViewById(R.id.webv);
				web.getSettings().setJavaScriptEnabled(true);
				web.loadUrl(oauth_url);
				web.setWebViewClient(new WebViewClient() {
					boolean authComplete = false;

					@Override
					public void onPageStarted(WebView view, String url,
							Bitmap favicon) {
						super.onPageStarted(view, url, favicon);
					}

					@Override
					public void onPageFinished(WebView view, String url) {
						super.onPageFinished(view, url);

						if (url.contains("oauth_verifier")
								&& authComplete == false) {
							authComplete = true;
							Log.e("Url onPageFinished ", "url onPageFinished: "
									+ url);
							Uri uri = Uri.parse(url);
							oauth_verifier = uri
									.getQueryParameter("oauth_verifier");

							auth_twitter_dialog.dismiss();
							new AccessTokenGet().execute();
						} else if (url.contains("dennied")) {
							auth_twitter_dialog.dismiss();
							Toast.makeText(mContext,
									"Sorry !, Permission Denied",
									Toast.LENGTH_SHORT).show();
						}
					}
				});
				auth_twitter_dialog.show();
				auth_twitter_dialog.setCancelable(true);

			} else {
				Toast.makeText(mContext,
						"Sorry !, Network Error or Invalid Credentials",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	/**
	 * AsyncTask class login twitter and get info user
	 * 
	 * @author MUI
	 * 
	 */
	private class AccessTokenGet extends AsyncTask<String, String, Boolean> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progress = new ProgressDialog(mContext);
			progress.setMessage("Fetching Data ...");
			progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progress.setIndeterminate(true);
			progress.show();
		}

		@Override
		protected Boolean doInBackground(String... params) {
			try {
				accessToken = twitter.getOAuthAccessToken(requestToken,
						oauth_verifier);
				SharedPreferences.Editor edit = pref.edit();
				edit.putString("ACCESS_TOKEN", accessToken.getToken());
				edit.putString("ACCESS_TOKEN_SECRET",
						accessToken.getTokenSecret());
				User user = twitter.showUser(accessToken.getUserId());
				userName = user.getName();
				profileUrl = user.getOriginalProfileImageURL();
				// edit.putString("name", user.getName());
				// edit.putString("avatar", user.getOriginalProfileImageURL());
				// edit.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
				Log.i(TAG, "username: " + user.getName());
				return true;

			} catch (TwitterException e) {
				e.printStackTrace();
				return false;
			}

		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (result) {

				progress.hide();
				Toast.makeText(mContext, "login twitter susscesfully",
						Toast.LENGTH_LONG).show();
				Intent intent = new Intent(mContext, ActivityRegister.class);
				intent.putExtra(UserInfo.USERNAME, userName);
				intent.putExtra("avatar", profileUrl);
				intent.setAction(ActivityRegister.BROADCAST_ACTION_TWITTER);
				intent.addCategory(Intent.CATEGORY_DEFAULT);
				sendBroadcast(intent);
				// setResult(ActivityRegister.RESULT_TWITTER);
				// ActivityLoginTwitter.this.finish();
			}
		}

	}

	/**
	 * class to postTweet
	 * 
	 * @author MUI
	 * 
	 */
	private class PostTweet extends AsyncTask<String, String, String> {

		private String status;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progress = new ProgressDialog(mContext);
			progress.setMessage("Posting tweet ...");
			progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progress.setIndeterminate(true);
			progress.show();
			Log.i(TAG, "post tweet");
		}

		@Override
		protected String doInBackground(String... params) {
			ConfigurationBuilder builder = new ConfigurationBuilder();
			builder.setOAuthConsumerKey(pref.getString("CONSUMER_KEY", ""));
			builder.setOAuthConsumerSecret(pref
					.getString("CONSUMER_SECRET", ""));

			AccessToken accessToken = new AccessToken(pref.getString(
					"ACCESS_TOKEN", ""), pref.getString("ACCESS_TOKEN_SECRET",
					""));
			Twitter twitter = new TwitterFactory(builder.build())
					.getInstance(accessToken);

			try {
				twitter4j.Status response = twitter.updateStatus(status);
				return response.toString();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;

		}

		@Override
		protected void onPostExecute(String res) {
			super.onPostExecute(res);
			if (res != null) {
				progress.dismiss();
				Toast.makeText(mContext, "Tweet Sucessfully Posted",
						Toast.LENGTH_SHORT).show();
				Log.i(TAG, "post tweet successfully");
			} else {
				progress.dismiss();
				Toast.makeText(mContext, "Error while tweeting !",
						Toast.LENGTH_SHORT).show();
				Log.i(TAG, "post tweet failed");
			}
		}

	}

	public Boolean isTwitterLoggedIn() {
		return pref.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
	}

	public void getInfoUser(User user) {
		userName = user.getName();
		userId = String.valueOf(user.getId());
		createAt = String.valueOf(user.getCreatedAt());
		userDescription = user.getDescription();
		profileUrl = user.getOriginalProfileImageURL();

	}
}
